package com.gitee.cui.websocket;

import com.gitee.cui.config.SystemConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;

/**
 * websocket协议编解码器测试服务端
 * @author cuiqingqiang
 * @version 1.0
 * @date 2021/11/1 15:10
 **/
public class WebSocketEchoServer {

    public static void main(String[] args) {
        runServer();
    }

    /**
     * 启动服务端
     */
    private static void runServer() {

        EventLoopGroup boss = new NioEventLoopGroup(1);
        EventLoopGroup worker = new NioEventLoopGroup();
        try {
            ServerBootstrap bootstrap = new ServerBootstrap();
            bootstrap.group(boss, worker)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.DEBUG))
                    .childHandler(new EchoInitializer());

            Channel channel = bootstrap.bind(SystemConfig.SOCKET_SERVER_PORT).sync().channel();
            ChannelFuture closeFuture = channel.closeFuture();
            closeFuture.sync();
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            worker.shutdownGracefully();
            boss.shutdownGracefully();
        }
    }

    /**
     * websocket回显服务初始化器
     */
    private static class EchoInitializer extends ChannelInitializer<SocketChannel> {

        @Override
        protected void initChannel(SocketChannel ch) throws Exception {
            ChannelPipeline pipeline = ch.pipeline();
            pipeline.addLast(new HttpRequestDecoder());
            pipeline.addLast(new HttpResponseEncoder());
            pipeline.addLast(new HttpObjectAggregator(65535));
            // 升级HTTP协议为websocket协议
            pipeline.addLast(new WebSocketServerProtocolHandler("/ws", "echo", true, 10 * 1024));
            // 添加网页处理器
            pipeline.addLast(new WebPageHandler());
            // 添加websocket协议的文本处理器
            pipeline.addLast(new TextWebSocketFrameHandler());
        }
    }
}
